<template>
  <q-layout ref="layout" view="Lhh lpr lFf" reveal>
    <!--横向toolbar菜单-->
    <q-toolbar slot="header">
      <q-btn flat v-go-back.single="store.backRoute" class="cordova-only electron-only">
        <q-icon name="arrow_back" />
      </q-btn>
      <q-toolbar-title>
        <q-icon
          v-show="store.icon"
          style="font-size: 2rem; margin-right: 5px;"
          :name="store.icon"
        />
        {{ store.title }}
      </q-toolbar-title>
      <!-- 音乐播放 -->
      <q-spinner-infinity color="orange" size="40px" />
      <q-btn flat class="within-iframe-hide" @click="foldMenu">
        <q-icon name="menu" />
      </q-btn>
    </q-toolbar>

    <!-- toolbar下二级tab -->
    <q-tabs
      slot="navigation"
      v-if="store.tabs.length > 0"
      :class="{'within-iframe-hide': !store.iframeTabs}"
    >
      <q-route-tab
        v-for="tab in store.tabs"
        :key="tab.hash"
        slot="title"
        :icon="tab.icon"
        :to="`/views/${store.hash}/${tab.hash}`"
        :label="tab.label"
        exact
        replace
      />
    </q-tabs>

    <!-- 左边菜单 -->
    <q-scroll-area
      slot="left"
      style="width: 100%; height: 100%;"
      class="bg-grey-3"
    >
      <q-side-link
            item
            to="/personal/sys-settings"
            replace
          >
          <div class="row flex-center" style="height: 150px;">
              <span>
                <img  :src="(customer.logoRes || 'statics/hg-logo-camera.png') | avatarView" 
                  style="height: 75px;width:75px;border-radius: 50%;"/>
              </span>
              <span>
                <div style="font-size:1.3rem;margin-left: 15px">
                    {{customer.nickname || '暂未登录'}}
                </div>
                <div :style="'font-size:2rem;margin-left: 15px;color:'+medalColor">
                    <q-icon name="assistant"/>
                </div>
              </span>
              <div>
                <q-icon name="edit"/>
                <span style="font-size: 0.9rem;color:#17536b;word-break:break-all;">
                  {{customer.summary || '小主太懒，什么也没说道' | contentLengthEllipsis(40)}}
                </span>
              </div>
          </div>
        </q-side-link>
      <q-list>
          <span>
              <q-tabs inverted>
                <q-route-tab small color="secondary"  slot="title" icon="home" label="首页" 
                  to="/menus" />
                <q-route-tab :alert="isAlert || false" color="secondary"  slot="title" icon="record voice over" label="系统消息" 
                  to="/sys/sys-notify"/>
                <q-route-tab :count="msgCount" color="secondary" slot="title" icon="email" label="我的通知"
                to="/personal/my-partake"/>
              </q-tabs>
          </span>

          <q-item-separator />
          <div v-for="category in routerList" :key="category.hash"> 
          <template v-if="category.features.length>0">
            <!-- <q-list-header>
              {{ category.title }}
            </q-list-header> -->
            <q-side-link
              item
              v-for="menu in category.features"
              :key="menu.hash"
              :to="`/${category.hash}/${menu.hash}`"
              replace
            >
              <q-item-side :icon="menu.icon" />
              <q-item-main :label="menu.title" />
              <q-item-side right icon="chevron_right" />
            </q-side-link>
            <q-item-separator />
          </template>
          <q-item-separator />
        </div>
        
        <!-- 🎵 播放 -->
        <audio src="statics/booty+music.mp3" controls="controls"></audio>
       
         <q-btn
            v-if="islogin"
            class="full-width"
            glossy  
            icon = "exit to app"
            color="dark"
            @click="logoutAction"
          >退出账户</q-btn>
         <q-btn
            v-else
            class="full-width"
            glossy  
            icon = "perm identity"
            color="dark"
            @click="tologin"
          >登录</q-btn>
      </q-list>
    </q-scroll-area>

    <q-transition enter="fadeIn" leave="fadeOut" mode="out-in" :duration="300">
      <router-view />
    </q-transition>
  </q-layout>
</template>
<script src="../utils/md5.js" type="text/javascript"></script>
<script>
import routerStore from "./router-store.js";
import routerList from "../router-list.js";
import customerApi from "../https/customerApi";
import openApi from "../https/openApi";
import { commonApi } from "../https/apiUrl";
import notifyApi from "../https/notifyApi";
import Storage from "../utils/storage";

import {
  QTransition,
  QScrollArea,
  QList,
  QSideLink,
  QListHeader,
  QItemSide,
  QItemMain,
  QItemSeparator,
  QBtn,
  QLayout,
  QToolbar,
  QToolbarTitle,
  QIcon,
  QTabs,
  QTab,
  QRouteTab,
  GoBack,
  Dialog,
  Toast,
  QSpinner,
  QSpinnerInfinity
} from "quasar";
import StorePouch from "../utils/StorePouch";


export default {
  components: {
    QTransition,
    QScrollArea,
    QList,
    QSideLink,
    QListHeader,
    QItemSide,
    QItemMain,
    QItemSeparator,
    QBtn,
    QLayout,
    QToolbar,
    QToolbarTitle,
    QIcon,
    QTabs,
    QTab,
    QRouteTab,
    Dialog,
    Toast,
    QSpinner,
    QSpinnerInfinity
  },
  directives: {
    GoBack
  },
  data() {
    return {
      newAppVersion: null,
      store: routerStore.state,
      islogin: false,
      isAlert: false, //是否显示系统消息的红点提醒
      msgCount: 0, //通知消息的数量
      customer: {},
      medalColor: "",
      medalOptions: {
        //等级选择
        COMMON: "",
        PLATINUM: "#9FB6CD",
        GOLDEN: "#FFEC8B",
        DIAMOND: "#C1CDC1",
        SVIP: "#68228B"
      }
    };
  },
  computed: {
    // 加载菜单项
    routerList: function() {
      routerList.forEach(_ele => {
        let menus = _ele.features;
        if (menus) {
          _ele.features = menus.filter(a => a.ismenu);
        }
      });
      // console.log("过滤菜单的路由结果：", routerList);
      return routerList;
    },
    isWin() {
      return this.$q.platform.is.platform == "win";
    },
    appVersion() {
       return global.APP_VERSION;
    }
  },
  mounted() {
    if (!this.isWin) {
      this.checkUpdate();
    }
    this.loadData();
    
  },
  methods: {
 
    checkUpdate() {
      //检查更新地址
      const _self = this;
      openApi.getAppVersion().then(res=>{
          const {status,data} = res;
          if(status == 200) {
            const _appVersion = data;
            _self.newAppVersion=_appVersion;
            console.log('当前app版本:',_appVersion)
            console.log('客户端app版本:',_self.appVersion)
            if(_self.appVersion && _self.appVersion != _appVersion) {
              console.log('版本需要更新')
              _self.versionToast();
            }            
          }
      }).catch(err=>{ })
    },
    foldMenu() {
      this.$refs.layout.toggleLeft();
      this.clearDatas();
      this.loadData();
    },
    clearDatas() {
      this.islogin = false;
      this.isAlert = false; //是否显示系统消息的红点提醒
      this.msgCount = 0; //通知消息的数量
      this.customer = {};
    },
    loadData() {
      const _curuser = Storage.curuser();
      console.log('当前用户信息：',_curuser);
      if (!_curuser) {
        const _this = this;
        StorePouch.tokenDbGet(StorePouch.tokenId(),function(_token){
              console.log('是否存在持久化:',_token);
              if(_token) {
                const querystring = require("querystring");
                const params = querystring.stringify({account:_token.account,password:_token.password,isAutoLogin:false});
                console.log("持久化登录:", params);
                customerApi.loginAccount(params).then(res=>{
                  if(res.status == 200) {
                      //将token存储到PouchDb中(解决移动端,localStorage异常问题)               
                      customerApi
                        .userinfo()
                        .then(res => {
                          const { status, data } = res;
                          if (status == 200 && data) {
                            Storage.saveuser(data);
                            _this.customer = data;
                            _this.islogin = true;
                            _this.medalColor = _this.medalOptions[_this.customer.grade];
                          }
                        })
                        .catch(err => {
                          Storage.removeCuruser();
                        });

                      this.$router.replace("/menus");
                    }
                }).catch(err=>{
                })
              }
            });


      } else {
        this.customer = _curuser;
        this.islogin = true;
      }
      this.medalColor = this.medalOptions[this.customer.grade];
      notifyApi //系统消息/我的通知的红点标识
        .notifyMark()
        .then(res => {
          const { status, data } = res;
          if (status == 200 && data) {
            this.isAlert = data.SYS_NOTIFY;
            this.msgCount = data.USER_NOTIFY_COUNT;
          }
        })
        .catch(err => {});
    },
    tologin() {
      this.$router.replace("/login");
    },
    logoutAction() {
      const self = this;
      //删除对话框，索引
      Dialog.create({
        title: "三思",
        message: `是否确定退出当前账号?`,
        position: "right",
        buttons: [
          {
            label: "确定",
            color: "negative",
            raised: true,
            handler() {
              customerApi
                .logout()
                .then(res => {
                  const { status } = res;
                  if (status >= 200 || status <= 302) {
                    console.log("退出登录成功");
                    StorePouch.tokenDbRemove(StorePouch.tokenId());
                    Storage.removeCuruser();
                    document.cookie="remember-me=1;Path=/;Max-Age=-1;";
                    window.location.reload();
                  }
                })
                .catch(err => {});
            }
          },
          {
            label: "手误",
            outline: true,
            handler() {
              console.log("取消删除");
            }
          }
        ]
      });
    },
    versionToast() {
      const _appVersion = this.newAppVersion;
      Toast.create({
        timeout: 5000,
        html: "检测到新的版本："+_appVersion,
        icon: "tag_faces",
        color: "orange",
        bgColor: "grey",
        button: {
          label: "点此更新",
          handler() {
             //调用浏览器打开下载链接，需要安装inappbrowser插件
            window.open(
              "http://c.himygirl.cn/api/ftp/hg-latest.apk",
              "_system",
              "location=yes"
            );
          }
        }
      });
    }
  }
};
</script>
